<template>
  <el-form :model="postform" status-icon :rules="rules" ref="postform" label-width="100px" >
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input type="password" v-model="postform.oldPassword" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input type="password" v-model="postform.newPassword" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="newPassword2">
      <el-input type="password" v-model="postform.newPassword2" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">修改密码</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { ChangePassword } from '@/api/user'

export default {
  name: 'modifyPassword',
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'))
      } else if (value !== this.postform.newPassword) {
        callback(new Error('两次输入新密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      postform: {
        oldPassword: '',
        newPassword: '',
        newPassword2: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 3, max: 32, message: '新密码长度在 3 到 32 个字符', trigger: 'blur' }
        ],
        newPassword2: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      var _this = this
      this.$refs['postform'].validate(valid => {
        if (valid) {
          _this.loading = true
          ChangePassword(_this.postform)
            .then(result => {
              _this.$message.success('密码修改成功')
              _this.$emit('successed', result)
              _this.loading = false
            })
            .catch(response => {
              _this.loading = false
            })
        }
      })
    },
    resetForm() {
      this.$refs['postform'].resetFields()
    }
  }
}
</script>
